package com.xiaoshuidi.cloud.module.iot.service.impl.thirdPartImpl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Maps;
import com.xiaoshuidi.cloud.framework.common.exception.ServiceException;
import com.xiaoshuidi.cloud.framework.common.exception.enums.GlobalErrorCodeConstants;
import com.xiaoshuidi.cloud.framework.common.pojo.CommonResult;
import com.xiaoshuidi.cloud.module.iot.api.device.vo.AmmeterInfoResModel;
import com.xiaoshuidi.cloud.module.iot.api.device.vo.WaterMeterCommonResponseModel;
import com.xiaoshuidi.cloud.module.iot.controller.admin.doorlock.vo.DeviceGetDailyPowerResModel;
import com.xiaoshuidi.cloud.module.iot.controller.admin.doorlock.vo.OperateThirdDeviceRequestModel;
import com.xiaoshuidi.cloud.module.iot.controller.admin.doorlock.vo.OperateThirdDeviceResponseModel;
import com.xiaoshuidi.cloud.module.iot.controller.admin.doorlock.vo.PullThirdDeviceRequestModel;
import com.xiaoshuidi.cloud.module.iot.dal.model.AccessTokenRequestModel;
import com.xiaoshuidi.cloud.module.iot.dal.model.AccessTokenResponseModel;
import com.xiaoshuidi.cloud.module.iot.dal.pojo.TbDeviceDo;
import com.xiaoshuidi.cloud.module.iot.dal.pojo.TbDoorlockPassword;
import com.xiaoshuidi.cloud.module.iot.dal.repository.DeviceOperationRepository;
import com.xiaoshuidi.cloud.module.iot.dal.repository.DeviceRepository;
import com.xiaoshuidi.cloud.module.iot.dal.repository.TbDoorLockPasswordRepository;
import com.xiaoshuidi.cloud.module.iot.enums.BrandEnum;
import com.xiaoshuidi.cloud.module.iot.enums.DeviceTypeEnum;
import com.xiaoshuidi.cloud.module.iot.enums.YinTongDevTypeEnum;
import com.xiaoshuidi.cloud.module.iot.service.AbstractThirdInstanceService;
import com.xiaoshuidi.cloud.module.iot.service.CacheService;
import com.xiaoshuidi.cloud.module.iot.uitils.DateUtils;
import com.xiaoshuidi.cloud.module.iot.uitils.MD5Util;
import com.xiaoshuidi.cloud.module.iot.uitils.RandomGenerator;
import com.xiaoshuidi.cloud.module.system.api.sms.SmsSendApi;
import com.xiaoshuidi.cloud.module.system.api.sms.dto.send.SmsSendSingleToUserReqDTO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

@Service("yinTongInstanceServiceImpl")
public class YinTongInstanceServiceImpl extends AbstractThirdInstanceService {

    private final static Logger LOGGER = LoggerFactory.getLogger(YinTongInstanceServiceImpl.class);
    private final static SimpleDateFormat FORMAT = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");


    @Autowired
    private CacheService cacheService;
    @Autowired
    private DeviceRepository deviceDataAccess;
    @Autowired
    private TbDoorLockPasswordRepository tbDoorLockPasswordDataAccess;
    @Autowired
    private DeviceOperationRepository deviceOperationDataAccess;
    @Resource
    private SmsSendApi smsFeignService;

    @Override
    public String getBrand() {
        return BrandEnum.YINTONGWULIAN.getBrand();
    }


    //银通物联获取所有设备
    @Value("${yintong.device.list}")
    private String yintongDeviceList;
    //银通物联门锁下发密码
    @Value("${yintong.addDoorLockPassword.url}")
    private String yintongAddDoorLockPasswordUrl;
    //银通物联门锁下发密码
    @Value("${yintong.editDoorLockPassword.url}")
    private String yintongEditDoorLockPasswordUrl;
    //银通物联门锁删除密码
    @Value("${yintong.delDoorLockPassword.url}")
    private String yintongDelDoorLockPasswordUrl;
    //银通物联设备冻结(水表关阀 电表断电、门锁清空密码)
    @Value("${yintong.freeze.url}")
    private String yintongFreezeUrl;
    //银通物联设备解冻(水表开阀、电表通电)
    @Value("${yintong.unfreeze.url}")
    private String yintongUnfreezeUrl;
    //银通物联获取设备读数(水表读数 电表读数、门锁电量)
    @Value("${yintong.readValue.url}")
    private String yintongReadValueUrl;
    //银通物联批量获取设备读数(水表读数，电表读数，门锁电量)
    @Value("${yintong.batchReadValue.url}")
    private String yintongBatchReadValueUrl;
    //银通物联获取开锁记录
    @Value("${yintong.openLog.url}")
    private String yintongOpenLogUrl;
    //银通物联获取设备状态，含所有信息
    @Value("${yintong.deviceInfo.url}")
    private String yintongDeviceInfoUrl;


    /**
     * 获取access_token
     *
     * @param accessTokenRequestModel
     * @return
     */
    @Override
    public AccessTokenResponseModel getAccessToken(AccessTokenRequestModel accessTokenRequestModel) throws Exception {
        //银通的token主要保存的就是timestamp和根据timestamp和签名生成的sign
        String timestamp = String.valueOf(new Date().getTime());
        String sign = MD5Util.MD5Encode(accessTokenRequestModel.getAppKey() + accessTokenRequestModel.getAppId() + timestamp).toUpperCase();
        String access_token = timestamp + "|" + sign;
        AccessTokenResponseModel accessTokenResponseModel = new AccessTokenResponseModel();
        accessTokenResponseModel.setAccessToken(access_token);
        //银通失效时间是120秒，我们设置90秒
        accessTokenResponseModel.setExpireTime(90L);
        return accessTokenResponseModel;
    }

    /**
     * 拉取设备
     *
     * @param pullThirdDeviceRequestModel
     * @return
     */
    @Override
    public List<TbDeviceDo> getDevice(PullThirdDeviceRequestModel pullThirdDeviceRequestModel) throws Exception {
        List<TbDeviceDo> tbDeviceDos = new ArrayList<>();
        String accessToken[] = pullThirdDeviceRequestModel.getAccessToken().split("\\|");
        String client_id = pullThirdDeviceRequestModel.getLoginName();
        header.put("timestamp", accessToken[0]);
        header.put("appId", client_id);
        header.put("sign", accessToken[1]);
        int pageNum = 1;
        int totalNum = 1;
        List<TbDeviceDo> existDevices = deviceDataAccess.getDeviceListByOneApiNo(pullThirdDeviceRequestModel.getTbAccountDo().getApiNo());
        List<String> existDevicesUuid = existDevices.stream().map
                (existDevice -> existDevice.getDeviceThirdNo()).collect(Collectors.toList());
        int retry = 0;
        while (pageNum <= totalNum) {
            JSONObject bodyParam = new JSONObject();
            bodyParam.put("pageNum", pageNum);//拉取3万条
            bodyParam.put("pageSize", 30000);//拉取3万条
            LOGGER.info("银通拉取设备，请求url:{},请求参数:{}{}", yintongDeviceList, bodyParam.toJSONString(), header);
            String result = HttpRequest.post(yintongDeviceList).body(JSONUtil.toJsonStr(bodyParam)).header("timestamp", accessToken[0])
                    .header("appId", client_id).header("sign", accessToken[1]).execute().body();
//            String result = HttpClientUtil.doPostJson(yintongDeviceList, bodyParam, header);
            LOGGER.info("银通拉取设备，返回结果:{}", result);
            if (StrUtil.isNotBlank(result)) {
                JSONObject resultJsonObject = JSONObject.parseObject(result);
                String ErrNo = resultJsonObject.getString("code");
                if ("0000".equals(ErrNo)) {
                    pageNum = pageNum + 1;
                    totalNum = resultJsonObject.getJSONObject("data").getInteger("pages");
                    JSONArray data_list = resultJsonObject.getJSONObject("data").getJSONArray("data");
                    if (CollUtil.isNotEmpty(data_list)) {
                        data_list = data_list.stream().filter(object ->
                                !existDevicesUuid.contains(((JSONObject) object).getString("devSn"))).collect(Collectors.toCollection(JSONArray::new));
                        if (CollUtil.isNotEmpty(data_list)) {
                            for (Iterator<Object> deviceIterator = data_list.iterator(); deviceIterator.hasNext(); ) {
                                JSONObject deviceInfo = (JSONObject) deviceIterator.next();
                                TbDeviceDo tbDeviceDo = new TbDeviceDo();
                                //1水表，2电表，3门锁
                                String type = deviceInfo.getString("devType");
                                //设备唯一标识
                                String devSn = deviceInfo.getString("devSn");
                                // 设备在线状态，1：在线；0：离线
                                Integer onoff = Optional.ofNullable(deviceInfo.getInteger("netStatus")).orElse(0);
                                // 设备合闸状态，1：断水断电；0：通水通电
                                Integer power = Optional.ofNullable(deviceInfo.getInteger("devStatus")).orElse(1);
                                tbDeviceDo.setDeviceThirdNo(devSn);
                                tbDeviceDo.setDeviceName(devSn);
                                tbDeviceDo.setDeviceModel("YT");
                                tbDeviceDo.setReportTime(LocalDateTime.now());
                                tbDeviceDo.setOnlineStatus(onoff == 1 ? 1 : 0);
                                tbDeviceDo.setPowerStatus(power == 0 ? 1 : 0);
                                Double value = Optional.ofNullable(deviceInfo.getDouble("readValue")).orElse(0.0);
                                if (type.equals(YinTongDevTypeEnum.LOCK.getCode())) {//门
                                    tbDeviceDo.setBatteryLevel(value);
                                    tbDeviceDo.setDeviceType(DeviceTypeEnum.DOORLOCK.getCode());
                                } else if (type.equals(YinTongDevTypeEnum.AMMETER.getCode())) {//电
                                    tbDeviceDo.setCurrentReading(value / 1000);
                                    tbDeviceDo.setDeviceType(DeviceTypeEnum.AMMETER.getCode());
                                } else if (type.equals(YinTongDevTypeEnum.COLD.getCode())) {//冷水
                                    tbDeviceDo.setCurrentReading(value / 1000);
                                    tbDeviceDo.setDeviceType(DeviceTypeEnum.COLD_WATERMETE_TYPE_ENUM.getCode());
                                } else if (type.equals(YinTongDevTypeEnum.HOT.getCode())) {//热水
                                    tbDeviceDo.setCurrentReading(value / 1000);
                                    tbDeviceDo.setDeviceType(DeviceTypeEnum.HOT_WATERMETE_TYPE_ENUM.getCode());
                                } else {
                                    continue;
                                }
                                tbDeviceDos.add(tbDeviceDo);
                            }
                        }

                    }
                    retry = 0;
                } else {
                    //请求失败重试5次，如果还失败则直接退出
                    if (retry > 5) {
                        String msg = pageNum > 1 ? "调用三方接口,拉取设备部分失败" : "调取三方接口，拉取设备全部失败";
                        throw new ServiceException(GlobalErrorCodeConstants.INTERNAL_SERVER_ERROR.getCode(), msg);
                    }
                }
            }
        }
        return tbDeviceDos;
    }

    /**
     * 第三方设备初始化操作
     *
     * @param thirdDeviceList
     * @param pullThirdDeviceRequestModel
     * @return
     */
    @Override
    public List<TbDeviceDo> initializeDeviceInfo(List<TbDeviceDo> thirdDeviceList, PullThirdDeviceRequestModel pullThirdDeviceRequestModel) {
        return null;
    }

    /**
     * 添加密码
     *
     * @param operateThirdDeviceRequestModel
     * @return
     */
    @Override
    public OperateThirdDeviceResponseModel addDoorLockPassword(OperateThirdDeviceRequestModel operateThirdDeviceRequestModel) throws Exception {
        OperateThirdDeviceResponseModel operateThirdDeviceResponseModel = new OperateThirdDeviceResponseModel();
        operateThirdDeviceResponseModel.setOperateResult(false);
        String type = "add";
        if (operateThirdDeviceRequestModel.getPasswordType().equals("1")) {
            operateThirdDeviceResponseModel = addDoorLockZxPassword(operateThirdDeviceRequestModel, type);
            Long passwordStartTime = operateThirdDeviceRequestModel.getPasswordStartTime();
            Date date = new Date(passwordStartTime);
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            String beginTime = sdf.format(date);

            Long passwordEndTime = operateThirdDeviceRequestModel.getPasswordEndTime();
            Date date1 = new Date(passwordEndTime);
            SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd");
            String endTime = sdf1.format(date1);

            Map<String, Object> templateParams = Maps.newHashMap();
                templateParams.put("password",operateThirdDeviceRequestModel.getPasswordContent());
                templateParams.put("begin",beginTime);
                templateParams.put("end",endTime);
                SmsSendSingleToUserReqDTO dto=new SmsSendSingleToUserReqDTO();
                dto.setTemplateParams(templateParams);
                if(operateThirdDeviceRequestModel.getGate() == null || !operateThirdDeviceRequestModel.getGate()) {
                    dto.setTemplateCode("user-sms-lockpassword");
                }else {
                    dto.setTemplateCode("user-sms-lockpassword2");
                }
                dto.setMobile(operateThirdDeviceRequestModel.getMobile());
            CommonResult<Long> longCommonResult = smsFeignService.sendSingleSmsToMember(dto);
            LOGGER.info("下发密码发送短信返回结果："+JSONObject.toJSONString(longCommonResult));

        } else if (operateThirdDeviceRequestModel.getPasswordType().equals("6")) {
            operateThirdDeviceResponseModel = addDoorLockLxPassword(operateThirdDeviceRequestModel);
        }
        return operateThirdDeviceResponseModel;
    }

    /**
     * 银通门锁添加在线密码
     *
     * @param operateThirdDeviceRequestModel
     * @return
     */
    private OperateThirdDeviceResponseModel addDoorLockZxPassword(OperateThirdDeviceRequestModel operateThirdDeviceRequestModel, String type) throws Exception {
        OperateThirdDeviceResponseModel operateThirdDeviceResponseModel = new OperateThirdDeviceResponseModel();
        String accessToken[] = operateThirdDeviceRequestModel.getAccessToken().split("\\|");
        String client_id = operateThirdDeviceRequestModel.getLoginName();
        header.put("timestamp", accessToken[0]);
        header.put("appId", client_id);
        header.put("sign", accessToken[1]);
        JSONObject bodyParam = new JSONObject();
        bodyParam.put("devSn", operateThirdDeviceRequestModel.getDeviceThirdNo());
        bodyParam.put("devType", YinTongDevTypeEnum.LOCK.getCode());
        JSONObject sonParam = new JSONObject();
        //pwdType  0永久使用  1单次使用  2时限使用（管理员密码只能使用永久密码）
        sonParam.put("pwd", operateThirdDeviceRequestModel.getPasswordContent());
        sonParam.put("pwdType", "2");
        sonParam.put("userId", operateThirdDeviceRequestModel.getMobile());
        sonParam.put("startTime", operateThirdDeviceRequestModel.getPasswordStartTime() / 1000);
        sonParam.put("endTime", operateThirdDeviceRequestModel.getPasswordEndTime() / 1000);
        sonParam.put("userName", operateThirdDeviceRequestModel.getMobile());
        bodyParam.put("param", sonParam);
        LOGGER.info("银通设置门锁离线密码，请求url:{},请求参数:{}", yintongAddDoorLockPasswordUrl, bodyParam.toJSONString());
        String result = HttpRequest.post(yintongAddDoorLockPasswordUrl).body(JSONUtil.toJsonStr(bodyParam)).header("timestamp", accessToken[0])
                .header("appId", client_id).header("sign", accessToken[1]).execute().body();
//        String result = HttpClientUtil.doPostJson(yintongAddDoorLockPasswordUrl, bodyParam, header);
        LOGGER.info("银通设置门锁离线密码，返回结果:{}", result);
        //商户自定义，对该密码的描述名称，必传参数
        JSONObject resultJsonObject = JSONObject.parseObject(result);
        String code = resultJsonObject.getString("code");
        if (code.equals("0000")) {
            JSONObject cache = new JSONObject();
            //{"passwordId":"","passwordContent":"","pwdType":"","actionTime":"yyyy-MM-dd HH:mm:ss","passwordStartTime":"","passwordEndTime":"","actionType":""}
            cache.put("passwordId", resultJsonObject.getString("uuid"));
            cache.put("pwdType", "2");
            cache.put("passwordContent", operateThirdDeviceRequestModel.getPasswordContent());
            cache.put("actionTime", DateUtils.getTimeStrBySdf(-1, FORMAT));
            cache.put("passwordStartTime", DateUtils.getTimeStrBySdf(operateThirdDeviceRequestModel.getPasswordStartTime(), FORMAT));
            cache.put("passwordEndTime", DateUtils.getTimeStrBySdf(operateThirdDeviceRequestModel.getPasswordEndTime(), FORMAT));
            cache.put("actionType", type);
            String uuid = resultJsonObject.getString("uuid");
            cacheService.putString("yintong:device:" + uuid, cache.toJSONString(), 3 * 24 * 3600);
            operateThirdDeviceResponseModel.setOperateResult(true);
            operateThirdDeviceResponseModel.setPasswordContent(operateThirdDeviceRequestModel.getPasswordContent());
            operateThirdDeviceResponseModel.setPasswordStatus(4);
            operateThirdDeviceResponseModel.setThirdPassId(uuid);
        } else {
            operateThirdDeviceResponseModel.setOperateResult(false);
            operateThirdDeviceResponseModel.setOperateMessage(resultJsonObject.getString("msg"));
        }
        return operateThirdDeviceResponseModel;
    }

    /**
     * 银通门锁添加离线密码
     *
     * @param operateThirdDeviceRequestModel
     * @return
     */
    private OperateThirdDeviceResponseModel addDoorLockLxPassword(OperateThirdDeviceRequestModel operateThirdDeviceRequestModel) throws Exception {
        OperateThirdDeviceResponseModel operateThirdDeviceResponseModel = new OperateThirdDeviceResponseModel();
        String accessToken[] = operateThirdDeviceRequestModel.getAccessToken().split("\\|");
        String client_id = operateThirdDeviceRequestModel.getLoginName();
        header.put("timestamp", accessToken[0]);
        header.put("appId", client_id);
        header.put("sign", accessToken[1]);
        JSONObject bodyParam = new JSONObject();
        bodyParam.put("devSn", operateThirdDeviceRequestModel.getDeviceThirdNo());
        bodyParam.put("devType", operateThirdDeviceRequestModel.getDeviceType());
        JSONObject sonParam = new JSONObject();
        //pwdType  0永久使用  1单次使用  2时限使用（管理员密码只能使用永久密码）
        sonParam.put("pwd", operateThirdDeviceRequestModel.getPasswordContent());
        sonParam.put("pwdType", "2");
        sonParam.put("userId", operateThirdDeviceRequestModel.getMobile());
        sonParam.put("startTime", operateThirdDeviceRequestModel.getPasswordStartTime() / 1000);
        sonParam.put("endTime", operateThirdDeviceRequestModel.getPasswordEndTime() / 1000);
        sonParam.put("userName", operateThirdDeviceRequestModel.getMobile());
        bodyParam.put("param", sonParam);
        LOGGER.info("银通设置门锁离线密码，请求url:{},请求参数:{}", yintongAddDoorLockPasswordUrl, bodyParam.toJSONString());
        String result = HttpRequest.post(yintongAddDoorLockPasswordUrl).body(JSONUtil.toJsonStr(bodyParam)).header("timestamp", accessToken[0])
                .header("appId", client_id).header("sign", accessToken[1]).execute().body();
//        String result = HttpClientUtil.doPostJson(yintongAddDoorLockPasswordUrl, bodyParam, header);
        LOGGER.info("银通设置门锁离线密码，返回结果:{}", result);
        //商户自定义，对该密码的描述名称，必传参数
        JSONObject resultJsonObject = JSONObject.parseObject(result);
        String code = resultJsonObject.getString("code");
        if (code.equals("0000")) {
            JSONObject cache = new JSONObject();
            //{"passwordId":"","passwordContent":"","pwdType":"","actionTime":"yyyy-MM-dd HH:mm:ss","passwordStartTime":"","passwordEndTime":"","actionType":""}
            cache.put("passwordId", resultJsonObject.getString("uuid"));
            cache.put("pwdType", "2");
            cache.put("passwordContent", operateThirdDeviceRequestModel.getPasswordContent());
            cache.put("actionTime", DateUtils.getTimeStrBySdf(-1, FORMAT));
            cache.put("passwordStartTime", DateUtils.getTimeStrBySdf(operateThirdDeviceRequestModel.getPasswordStartTime(), FORMAT));
            cache.put("passwordEndTime", DateUtils.getTimeStrBySdf(operateThirdDeviceRequestModel.getPasswordEndTime(), FORMAT));
            cache.put("actionType", "add");
            String uuid = resultJsonObject.getString("uuid");
            cacheService.putString("yintong:device:" + uuid, cache.toJSONString(), 3 * 24 * 3600);
            operateThirdDeviceResponseModel.setOperateResult(true);
            operateThirdDeviceResponseModel.setPasswordContent(operateThirdDeviceRequestModel.getPasswordContent());
            operateThirdDeviceResponseModel.setPasswordStatus(1);
        } else {
            operateThirdDeviceResponseModel.setOperateResult(false);
            operateThirdDeviceResponseModel.setOperateMessage(resultJsonObject.getString("msg"));
        }
        return operateThirdDeviceResponseModel;
    }

    /**
     * 获取动态密码
     *
     * @param operateThirdDeviceRequestModel
     * @return
     */
    @Override
    public OperateThirdDeviceResponseModel getDynamicDoorLockPassword(OperateThirdDeviceRequestModel operateThirdDeviceRequestModel) throws Exception {
        OperateThirdDeviceResponseModel operateThirdDeviceResponseModel = new OperateThirdDeviceResponseModel();
        if (StrUtil.isNotBlank(operateThirdDeviceRequestModel.getPasswordContent())) {
            operateThirdDeviceRequestModel.setPasswordContent(RandomGenerator.generateNumerString(6));
        }
        String accessToken[] = operateThirdDeviceRequestModel.getAccessToken().split("\\|");
        String client_id = operateThirdDeviceRequestModel.getLoginName();
        header.put("timestamp", accessToken[0]);
        header.put("appId", client_id);
        header.put("sign", accessToken[1]);
        JSONObject bodyParam = new JSONObject();
        bodyParam.put("devSn", operateThirdDeviceRequestModel.getDeviceThirdNo());
        bodyParam.put("devType", YinTongDevTypeEnum.LOCK.getCode());
        JSONObject sonParam = new JSONObject();
        //pwdType  0永久使用  1单次使用  2时限使用（管理员密码只能使用永久密码）
        sonParam.put("pwd", operateThirdDeviceRequestModel.getPasswordContent());
        sonParam.put("pwdType", "1");
        sonParam.put("userId", operateThirdDeviceRequestModel.getMobile());
        sonParam.put("userName", operateThirdDeviceRequestModel.getMobile());
//        sonParam.put("startTime",operateThirdDeviceRequestModel.getPasswordStartTime()/1000);
//        sonParam.put("endTime",operateThirdDeviceRequestModel.getPasswordEndTime()/1000);
        bodyParam.put("param", sonParam);
        LOGGER.info("银通设置门锁离线密码，请求url:{},请求参数:{}", yintongAddDoorLockPasswordUrl, bodyParam.toJSONString());
//        String result = HttpClientUtil.doPostJson(yintongAddDoorLockPasswordUrl, bodyParam, header);
        String result = HttpRequest.post(yintongAddDoorLockPasswordUrl).body(JSONUtil.toJsonStr(bodyParam)).header("timestamp", accessToken[0])
                .header("appId", client_id).header("sign", accessToken[1]).execute().body();
        LOGGER.info("银通设置门锁离线密码，返回结果:{}", result);
        //商户自定义，对该密码的描述名称，必传参数
        JSONObject resultJsonObject = JSONObject.parseObject(result);
        String code = resultJsonObject.getString("code");
        if (code.equals("0000")) {
            JSONObject cache = new JSONObject();
            //{"passwordId":"","passwordContent":"","pwdType":"","actionTime":"yyyy-MM-dd HH:mm:ss","passwordStartTime":"","passwordEndTime":"","actionType":""}
            cache.put("passwordId", resultJsonObject.getString("uuid"));
            cache.put("pwdType", "1");
            cache.put("passwordContent", operateThirdDeviceRequestModel.getPasswordContent());
            cache.put("actionTime", DateUtils.getTimeStrBySdf(-1, FORMAT));
            cache.put("passwordStartTime", DateUtils.getTimeStrBySdf(operateThirdDeviceRequestModel.getPasswordStartTime(), FORMAT));
            cache.put("passwordEndTime", DateUtils.getTimeStrBySdf(operateThirdDeviceRequestModel.getPasswordEndTime(), FORMAT));
            cache.put("actionType", "add");
            cacheService.putString("yintong:device:" + resultJsonObject.getString("uuid"), cache.toJSONString(), 3 * 24 * 3600);
            operateThirdDeviceResponseModel.setOperateResult(true);
            operateThirdDeviceResponseModel.setPasswordContent(operateThirdDeviceRequestModel.getPasswordContent());
            operateThirdDeviceResponseModel.setPasswordStatus(4);
        } else {
            operateThirdDeviceResponseModel.setOperateResult(false);
            operateThirdDeviceResponseModel.setOperateMessage(resultJsonObject.getString("msg"));
        }
        return operateThirdDeviceResponseModel;
    }


    /**
     * 刷新电表信息
     *
     * @param tbDeviceDo
     * @param operateThirdDeviceRequestModel
     * @return
     */
    @Override
    public AmmeterInfoResModel refreshAmmeterInfo(TbDeviceDo tbDeviceDo, OperateThirdDeviceRequestModel operateThirdDeviceRequestModel) throws Exception {
        AmmeterInfoResModel ammeterInfoResModel = new AmmeterInfoResModel();
        operateThirdDeviceRequestModel.setDeviceThirdNo(tbDeviceDo.getDeviceThirdNo());
        JSONObject resultJsonObject = JSONObject.parseObject(getInfoRespResult(operateThirdDeviceRequestModel, YinTongDevTypeEnum.AMMETER.getCode()));
        String ErrNo = resultJsonObject.getString("code");
        if ("0000".equals(ErrNo)) {
            JSONObject data = resultJsonObject.getJSONObject("data");
            // 设备在线状态，1：在线；2：不在线
            Integer onoff_line = Optional.ofNullable(data.getInteger("netStatus")).orElse(0);
            // 电表合闸状态，0：通电，1：断电
            Integer enable_state = Optional.ofNullable(data.getInteger("devStatus")).orElse(0);
            //当前电表用电量
            Double consume_amount = Optional.ofNullable(data.getDouble("readValue")).orElse(0.0) / 1000;
            // 当前电表用电量刷新时间戳，单位MS
            Long consume_amount_time = Optional.ofNullable(data.getLong("collectTime")).orElseGet(() -> new Date().getTime());
            ammeterInfoResModel.setReportTime(new Date(consume_amount_time));
            ammeterInfoResModel.setCurrentReading(consume_amount);
            ammeterInfoResModel.setOnlineStatus(onoff_line == 1 ? 1 : 0);
            ammeterInfoResModel.setPowerStatus(enable_state == 0 ? 1 : 0);
        }
        return ammeterInfoResModel;
    }


    private String getInfoRespResult(OperateThirdDeviceRequestModel operateThirdDeviceRequestModel, String devType) {
        String accessToken[] = operateThirdDeviceRequestModel.getAccessToken().split("\\|");
        String client_id = operateThirdDeviceRequestModel.getLoginName();
        header.put("timestamp", accessToken[0]);
        header.put("appId", client_id);
        header.put("sign", accessToken[1]);
        JSONObject bodyParam = new JSONObject();
        bodyParam.put("devSn", operateThirdDeviceRequestModel.getDeviceThirdNo());
        bodyParam.put("devType", devType);
        LOGGER.info("银通获取设备信息,请求url:{},请求参数:{}{}", yintongDeviceInfoUrl, bodyParam.toJSONString(), header);
//        String result = HttpClientUtil.doPostJson(yintongDeviceInfoUrl, bodyParam, header);
        String result = HttpRequest.post(yintongDeviceInfoUrl).body(JSONUtil.toJsonStr(bodyParam)).header("timestamp", accessToken[0])
                .header("appId", client_id).header("sign", accessToken[1]).execute().body();
        LOGGER.info("银通获取设备信息,返回结果:{}", result);
        return result;
    }

    /**
     * 水电表－日冻结数据查询
     *
     * @param operateThirdDeviceRequestModel
     * @return
     */
    @Override
    public List<DeviceGetDailyPowerResModel> getDailyPower(OperateThirdDeviceRequestModel operateThirdDeviceRequestModel) {
        return null;
    }

    /**
     * 修改密码（在线）
     *
     * @param operateThirdDeviceRequestModel
     * @return
     */
    @Override
    public OperateThirdDeviceResponseModel updateDoorLockPassword(OperateThirdDeviceRequestModel operateThirdDeviceRequestModel) throws Exception {
        OperateThirdDeviceResponseModel operateThirdDeviceResponseModel = new OperateThirdDeviceResponseModel();
        String accessToken[] = operateThirdDeviceRequestModel.getAccessToken().split("\\|");
        String client_id = operateThirdDeviceRequestModel.getLoginName();
        header.put("timestamp", accessToken[0]);
        header.put("appId", client_id);
        header.put("sign", accessToken[1]);
        JSONObject bodyParam = new JSONObject();
        bodyParam.put("devSn", operateThirdDeviceRequestModel.getDeviceThirdNo());
        bodyParam.put("devType", YinTongDevTypeEnum.LOCK.getCode());
        JSONObject sonParam = new JSONObject();
        //pwdType  0永久使用  1单次使用  2时限使用（管理员密码只能使用永久密码）
        sonParam.put("pwd", operateThirdDeviceRequestModel.getPasswordContent());
        sonParam.put("pwdType", "2");
        sonParam.put("userId", operateThirdDeviceRequestModel.getMobile());
        sonParam.put("startTime", operateThirdDeviceRequestModel.getPasswordStartTime() / 1000);
        sonParam.put("endTime", operateThirdDeviceRequestModel.getPasswordEndTime() / 1000);
        sonParam.put("userName", operateThirdDeviceRequestModel.getMobile());
        bodyParam.put("param", sonParam);
        LOGGER.info("银通修改密码，请求url:{},请求参数:{}", yintongEditDoorLockPasswordUrl, bodyParam.toJSONString());
//        String result = HttpClientUtil.doPostJson(yintongEditDoorLockPasswordUrl, bodyParam, header);
        String result = HttpRequest.post(yintongEditDoorLockPasswordUrl).body(JSONUtil.toJsonStr(bodyParam)).header("timestamp", accessToken[0])
                .header("appId", client_id).header("sign", accessToken[1]).execute().body();
        LOGGER.info("银通修改密码，返回结果:{}", result);
        //商户自定义，对该密码的描述名称，必传参数
        JSONObject resultJsonObject = JSONObject.parseObject(result);
        String code = resultJsonObject.getString("code");
        if (code.equals("0000")) {
            JSONObject cache = new JSONObject();
            TbDoorlockPassword tbDoorlockPassword = tbDoorLockPasswordDataAccess.getDoorLockPasswordByDeviceNo(operateThirdDeviceRequestModel.getDeviceThirdNo(), operateThirdDeviceRequestModel.getPasswordId());
            if (null != tbDoorlockPassword) {
                cache.put("oldPasswordContent", tbDoorlockPassword.getPassword());
                cache.put("oldPasswordStartTime", tbDoorlockPassword.getValidStarttime());
                cache.put("oldPasswordEndTime", tbDoorlockPassword.getValidEndtime());
            }
            cache.put("passwordId", resultJsonObject.getString("uuid"));
            cache.put("pwdType", "2");
            cache.put("passwordContent", operateThirdDeviceRequestModel.getPasswordContent());
            cache.put("actionTime", DateUtils.getTimeStrBySdf(-1, FORMAT));
            cache.put("passwordStartTime", DateUtils.getTimeStrBySdf(operateThirdDeviceRequestModel.getPasswordStartTime(), FORMAT));
            cache.put("passwordEndTime", DateUtils.getTimeStrBySdf(operateThirdDeviceRequestModel.getPasswordEndTime(), FORMAT));
            cache.put("actionType", "edit");
//            String passwordId = operateThirdDeviceRequestModel.getPasswordId();
            String uuid = resultJsonObject.getString("uuid");
            cacheService.putString("yintong:device:" + uuid, cache.toJSONString(), 3 * 24 * 3600);
            operateThirdDeviceResponseModel.setOperateResult(true);
            operateThirdDeviceResponseModel.setPasswordContent(operateThirdDeviceRequestModel.getPasswordContent());
            operateThirdDeviceResponseModel.setPasswordStatus(4);
            operateThirdDeviceResponseModel.setThirdPassId(uuid);
        } else {
            operateThirdDeviceResponseModel.setOperateResult(false);
            operateThirdDeviceResponseModel.setOperateMessage(resultJsonObject.getString("msg"));
        }
        return operateThirdDeviceResponseModel;
    }

    /**
     * 冻结密码 调用的删除接口，解冻实际上再调用删除
     * 密码状态 有效->执行中->冻结->执行中->有效（过期）
     *
     * @param operateThirdDeviceRequestModel 冻结请求
     * @return
     */
    @Override
    public OperateThirdDeviceResponseModel frozenDoorLockPassword(OperateThirdDeviceRequestModel operateThirdDeviceRequestModel) throws Exception {
        String type = "frozen";
        LOGGER.info("银通物联进行设备{}的密码{}进行冻结", operateThirdDeviceRequestModel.getDeviceThirdNo(), operateThirdDeviceRequestModel.getPasswordId());
        OperateThirdDeviceResponseModel operateThirdDeviceResponseModel = doDel(operateThirdDeviceRequestModel, type);
        // 冻结是执行中
        operateThirdDeviceResponseModel.setPasswordStatus(4);
        return operateThirdDeviceResponseModel;
    }

    /**
     * 解冻密码
     * 冻结->执行中
     *
     * @param operateThirdDeviceRequestModel
     * @return
     */
    @Override
    public OperateThirdDeviceResponseModel unfrozenDoorLockPassword(OperateThirdDeviceRequestModel operateThirdDeviceRequestModel) throws Exception {
        OperateThirdDeviceResponseModel resp = new OperateThirdDeviceResponseModel();
        String passwordId = operateThirdDeviceRequestModel.getPasswordId();
        String deviceNo = operateThirdDeviceRequestModel.getDeviceNo();
        // 先查找密码，若是密码的结束时间已经结束,则直接告诉他冻结失败；否则，将按照旧的密码id重新下发密码,密码内容一致，有效时间一致，类型为解冻
        List<TbDoorlockPassword> allPassList = tbDoorLockPasswordDataAccess.findDoorLockPasswordByDeviceNo(deviceNo);
        if (CollectionUtils.isEmpty(allPassList)) {
            resp.setOperateResult(Boolean.FALSE);
            return resp;
        }
        List<TbDoorlockPassword> targetPwdList = allPassList.stream().filter(pwd -> pwd.getThirdPasswordId().equals(passwordId) &&
                String.valueOf(pwd.getPasswordStatus()).equals("0") && String.valueOf(pwd.getStatus()).equals("1")).collect(Collectors.toList());
        if (targetPwdList.isEmpty()) {
            resp.setOperateResult(Boolean.FALSE);
            return resp;
        }
        TbDoorlockPassword targetPwd = targetPwdList.get(0);
        Date validEndtime = targetPwd.getValidEndtime();
        if (!validEndtime.after(new Date())) {
            // 若是密码结束时间早于当前，将给出三天的有效时间
            validEndtime = new Date(validEndtime.getTime() + 100 * 60 * 60 * 24 * 3);
        }
        // 下发密码
        String type = "unFrozen";
        operateThirdDeviceRequestModel.setPasswordStartTime(targetPwd.getValidStarttime().getTime());
        operateThirdDeviceRequestModel.setPasswordEndTime(targetPwd.getValidEndtime().getTime());
        operateThirdDeviceRequestModel.setPasswordContent(targetPwd.getPassword());
        operateThirdDeviceRequestModel.setPasswordId(targetPwd.getThirdPasswordId());
        operateThirdDeviceRequestModel.setMobile(targetPwd.getMemberMobile());
        operateThirdDeviceRequestModel.setDeviceThirdNo(operateThirdDeviceRequestModel.getDeviceThirdNo());
        return addDoorLockZxPassword(operateThirdDeviceRequestModel, type);
    }

    /**
     * 电表合闸
     * 2电表
     *
     * @param operateThirdDeviceRequestModel
     * @return
     */
    @Override
    public OperateThirdDeviceResponseModel switchAmmeterOn(OperateThirdDeviceRequestModel operateThirdDeviceRequestModel) throws Exception {
        return switchOnOrOff(operateThirdDeviceRequestModel, YinTongDevTypeEnum.AMMETER.getCode(), yintongUnfreezeUrl);
    }

    /**
     * 电表跳闸
     * 2电表
     *
     * @param operateThirdDeviceRequestModel
     * @return
     */
    @Override
    public OperateThirdDeviceResponseModel switchAmmeterOff(OperateThirdDeviceRequestModel operateThirdDeviceRequestModel) throws Exception {
        return switchOnOrOff(operateThirdDeviceRequestModel, YinTongDevTypeEnum.AMMETER.getCode(), yintongFreezeUrl);
    }


    private OperateThirdDeviceResponseModel switchOnOrOff(OperateThirdDeviceRequestModel operateThirdDeviceRequestModel, String devType, String url) throws Exception {
        OperateThirdDeviceResponseModel operateThirdDeviceResponseModel = new OperateThirdDeviceResponseModel();
        String accessToken[] = operateThirdDeviceRequestModel.getAccessToken().split("\\|");
        String client_id = operateThirdDeviceRequestModel.getLoginName();
        header.put("timestamp", accessToken[0]);
        header.put("appId", client_id);
        header.put("sign", accessToken[1]);
        JSONObject bodyParam = new JSONObject();
        bodyParam.put("devSn", operateThirdDeviceRequestModel.getDeviceThirdNo());
        bodyParam.put("devType", devType);
        LOGGER.info("银通冻结解冻设备，请求url:{},请求参数:{}", url, bodyParam.toJSONString());
//        String result = HttpClientUtil.doPostJson(url, bodyParam, header);
        String result = HttpRequest.post(url).body(JSONUtil.toJsonStr(bodyParam)).header("timestamp", accessToken[0])
                .header("appId", client_id).header("sign", accessToken[1]).execute().body();
        LOGGER.info("银通冻结解冻设备，返回结果:{}", result);
        //商户自定义，对该密码的描述名称，必传参数
        JSONObject resultJsonObject = JSONObject.parseObject(result);
        String code = resultJsonObject.getString("code");
        if (code.equals("0000")) {
            if (url.equals(yintongFreezeUrl)) {
                LOGGER.info("银通冻结设备，存redis:键{}-值{}", "yintong:device:" + resultJsonObject.getString("uuid"), "1");
                cacheService.putString("yintong:device:" + resultJsonObject.getString("uuid"), "1", 3 * 24 * 3600);
                LOGGER.info("银通冻结设备，取redis:值=={}", cacheService.getString("yintong:device:" + resultJsonObject.getString("uuid")));
            }
            if (url.equals(yintongUnfreezeUrl)) {
                LOGGER.info("银通解冻设备，存redis:键{}-值{}", "yintong:device:" + resultJsonObject.getString("uuid"), "0");
                cacheService.putString("yintong:device:" + resultJsonObject.getString("uuid"), "0", 3 * 24 * 3600);
                LOGGER.info("银通解冻设备，取redis:值=={}", cacheService.getString("yintong:device:" + resultJsonObject.getString("uuid")));
            }
            operateThirdDeviceResponseModel.setOperateResult(true);
        } else {
            operateThirdDeviceResponseModel.setOperateResult(false);
            operateThirdDeviceResponseModel.setOperateMessage(resultJsonObject.getString("msg"));
        }
        return operateThirdDeviceResponseModel;
    }


    /**
     * 删除密码
     *
     * @param operateThirdDeviceRequestModel
     * @return
     */
    @Override
    public OperateThirdDeviceResponseModel deleteDoorLockPassword(OperateThirdDeviceRequestModel operateThirdDeviceRequestModel) throws Exception {
        String type = "del";
        return doDel(operateThirdDeviceRequestModel, type);
    }

    private OperateThirdDeviceResponseModel doDel(OperateThirdDeviceRequestModel operateThirdDeviceRequestModel, String type) throws Exception {
        OperateThirdDeviceResponseModel operateThirdDeviceResponseModel = new OperateThirdDeviceResponseModel();
        String accessToken[] = operateThirdDeviceRequestModel.getAccessToken().split("\\|");
        String client_id = operateThirdDeviceRequestModel.getLoginName();
        header.put("timestamp", accessToken[0]);
        header.put("appId", client_id);
        header.put("sign", accessToken[1]);
        JSONObject bodyParam = new JSONObject();
        bodyParam.put("devSn", operateThirdDeviceRequestModel.getDeviceThirdNo());
        bodyParam.put("devType", YinTongDevTypeEnum.LOCK.getCode());
        JSONObject sonParam = new JSONObject();
        //pwdType  0永久使用  1单次使用  2时限使用（管理员密码只能使用永久密码）
        sonParam.put("pwd", operateThirdDeviceRequestModel.getPasswordContent());
        sonParam.put("pwdType", "2");
        sonParam.put("userId", operateThirdDeviceRequestModel.getMobile());
        bodyParam.put("param", sonParam);
        LOGGER.info("银通设置门锁删除在线密码，请求url:{},请求参数:{}", yintongDelDoorLockPasswordUrl, bodyParam.toJSONString());
//        String result = HttpClientUtil.doPostJson(yintongDelDoorLockPasswordUrl, bodyParam, header);

        String result = HttpRequest.post(yintongDelDoorLockPasswordUrl).body(JSONUtil.toJsonStr(bodyParam)).header("timestamp", accessToken[0])
                .header("appId", client_id).header("sign", accessToken[1]).execute().body();
        LOGGER.info("银通设置门锁删除在线密码，返回结果:{}", result);
        //商户自定义，对该密码的描述名称，必传参数
        JSONObject resultJsonObject = JSONObject.parseObject(result);
        String code = resultJsonObject.getString("code");
        if (code.equals("0000")) {
            JSONObject cache = new JSONObject();
            cache.put("passwordId", resultJsonObject.getString("uuid"));
            cache.put("pwdType", "2");
            cache.put("actionTime", DateUtils.getTimeStrBySdf(0l, FORMAT));
            cache.put("actionType", type);
            String uuid = resultJsonObject.getString("uuid");
            cacheService.putString("yintong:device:" + uuid, cache.toJSONString(), 3 * 24 * 3600);
            operateThirdDeviceResponseModel.setThirdPassId(uuid);
            operateThirdDeviceResponseModel.setOperateResult(true);
        } else {
            operateThirdDeviceResponseModel.setOperateResult(false);
            operateThirdDeviceResponseModel.setOperateMessage(resultJsonObject.getString("msg"));
        }
        return operateThirdDeviceResponseModel;
    }

    /**
     * 刷新水表信息
     *
     * @param waterMeterCommonResponseModel
     * @param operateThirdDeviceRequestModel
     * @return
     */
    @Override
    public WaterMeterCommonResponseModel refreshWatermeterInfo(WaterMeterCommonResponseModel waterMeterCommonResponseModel, OperateThirdDeviceRequestModel operateThirdDeviceRequestModel) throws Exception {
        waterMeterCommonResponseModel.setOperateResult(false);
        operateThirdDeviceRequestModel.setDeviceThirdNo(waterMeterCommonResponseModel.getDeviceThirdNo());
        String type = YinTongDevTypeEnum.COLD.getCode();
        if (DeviceTypeEnum.HOT_WATERMETE_TYPE_ENUM.getCode().equals(waterMeterCommonResponseModel.getDeviceType())) {
            type = YinTongDevTypeEnum.HOT.getCode();
        }
        JSONObject resultJsonObject = JSONObject.parseObject(getInfoRespResult(operateThirdDeviceRequestModel, type));
        String errNo = resultJsonObject.getString("code");
        if ("0000".equals(errNo)) {
            JSONObject data = resultJsonObject.getJSONObject("data");
            // 设备在线状态，1：在线；2：不在线
            Integer onoff_line = Optional.ofNullable(data.getInteger("netStatus")).orElse(0);
            // 水表合闸状态，1：断水，0：合闸通水
            Integer enable_state = Optional.ofNullable(data.getInteger("devStatus")).orElse(0);
            //水表用量
            Double consume_amount = Optional.ofNullable(data.getDouble("readValue")).orElse(0.0) / 1000;
            // 当前刷新时间戳，单位MS
            Long consume_amount_time = Optional.ofNullable(data.getLong("collectTime")).orElseGet(() -> new Date().getTime());
            waterMeterCommonResponseModel.setReportTime(new Date(consume_amount_time));
            waterMeterCommonResponseModel.setOnlineStatus(onoff_line == 1 ? 1 : 0);
            waterMeterCommonResponseModel.setCurrentReading(consume_amount);
            waterMeterCommonResponseModel.setOperateResult(true);
            waterMeterCommonResponseModel.setPowerStatus(enable_state == 0 ? 1 : 0);
        }
        return waterMeterCommonResponseModel;
    }

    /**
     * 门锁刷新
     *
     * @param operateThirdDeviceRequestModel
     * @return
     */
    @Override
    public OperateThirdDeviceResponseModel getDoorLockStatus(OperateThirdDeviceRequestModel operateThirdDeviceRequestModel) throws Exception {
        OperateThirdDeviceResponseModel operateThirdDeviceResponseModel = new OperateThirdDeviceResponseModel();
        operateThirdDeviceResponseModel.setOperateResult(false);
        operateThirdDeviceRequestModel.setDeviceThirdNo(operateThirdDeviceRequestModel.getDeviceThirdNoList().get(0));//默认是第一个
        JSONObject resultJsonObject = JSONObject.parseObject(getInfoRespResult(operateThirdDeviceRequestModel, YinTongDevTypeEnum.LOCK.getCode()));
        String errNo = resultJsonObject.getString("code");
        if ("0000".equals(errNo)) {
            JSONObject data = resultJsonObject.getJSONObject("data");
            // 设备在线状态，1：在线；2：不在线
            Integer onoff_line = Optional.ofNullable(data.getInteger("netStatus")).orElse(0);
            // 1：冻结中不可用，0：解冻
            Integer enable_state = Optional.ofNullable(data.getInteger("devStatus")).orElse(0);
            //电量
            Double consume_amount = Optional.ofNullable(data.getDouble("readValue")).orElse(0.0);
            operateThirdDeviceResponseModel.setOnlineStatus(onoff_line == 1 ? 1 : 0);
            operateThirdDeviceResponseModel.setBatteryLevel(consume_amount);
            operateThirdDeviceResponseModel.setOperateResult(true);
        }
        return operateThirdDeviceResponseModel;
    }


    /**
     * 获取门锁开门记录
     *
     * @param operateThirdDeviceRequestModel
     * @return
     */
    @Override
    public OperateThirdDeviceResponseModel getOpenLockRecordes(OperateThirdDeviceRequestModel operateThirdDeviceRequestModel) throws Exception {
        OperateThirdDeviceResponseModel operateThirdDeviceResponseModel = new OperateThirdDeviceResponseModel();
        String accessToken[] = operateThirdDeviceRequestModel.getAccessToken().split("\\|");
        String client_id = operateThirdDeviceRequestModel.getLoginName();
        header.put("timestamp", accessToken[0]);
        header.put("appId", client_id);
        header.put("sign", accessToken[1]);
        JSONObject bodyParam = new JSONObject();
        bodyParam.put("devSn", operateThirdDeviceRequestModel.getDeviceThirdNo());
        bodyParam.put("devType", YinTongDevTypeEnum.LOCK.getCode());
        bodyParam.put("startTime", operateThirdDeviceRequestModel.getQueryBeginTime() / 1000);
        bodyParam.put("endTime", operateThirdDeviceRequestModel.getQueryEndTime() / 1000);
        bodyParam.put("pageSize", 50);
        LOGGER.info("银通获取开锁记录，请求url:{},请求参数:{}", yintongOpenLogUrl, bodyParam.toJSONString());
//        String result = HttpClientUtil.doPostJson(yintongOpenLogUrl, bodyParam, header);
        String result = HttpRequest.post(yintongOpenLogUrl).body(JSONUtil.toJsonStr(bodyParam)).header("timestamp", accessToken[0])
                .header("appId", client_id).header("sign", accessToken[1]).execute().body();
        LOGGER.info("银通获取开锁记录，返回结果:{}", result);
        JSONObject resultJsonObject = JSONObject.parseObject(result);
        String errNo = resultJsonObject.getString("code");
        if ("0000".equals(errNo)) {
            operateThirdDeviceResponseModel.setOperateResult(true);
            JSONObject dataJsobObject = resultJsonObject.getJSONObject("data");
            JSONArray listJsonArray = dataJsobObject.getJSONArray("data");
            JSONArray jsonArray = new JSONArray();
            for (int i = 0; i < listJsonArray.size(); i++) {
                JSONObject dataJsonObject = listJsonArray.getJSONObject(i);
                //公共接口已经固定取passwordId,在此变换key
                dataJsonObject.put("passwordId", dataJsonObject.getString("userId"));
                //公共接口已经固定取openTime，在此变换key
                dataJsonObject.put("openTime", dataJsonObject.getString("openTime"));
                dataJsonObject.put("openType", "1");
                jsonArray.add(dataJsonObject);
            }
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("json", jsonArray);
            operateThirdDeviceResponseModel.setDataJson(jsonObject);
        } else {
            operateThirdDeviceResponseModel.setOperateResult(false);
            operateThirdDeviceResponseModel.setOperateMessage(resultJsonObject.getString("message"));
        }
        return operateThirdDeviceResponseModel;
    }

    /**
     * 冷水表关阀停水
     * @param operateThirdDeviceRequestModel
     * @return
     * @throws Exception
     */
    @Override
    public OperateThirdDeviceResponseModel switchColdWaterMeterOff(OperateThirdDeviceRequestModel operateThirdDeviceRequestModel) throws Exception {
        return switchOnOrOff(operateThirdDeviceRequestModel, YinTongDevTypeEnum.COLD.getCode(), yintongFreezeUrl);
    }

    /**
     * 热水表关阀停水
     * @param operateThirdDeviceRequestModel
     * @return
     * @throws Exception
     */
    @Override
    public OperateThirdDeviceResponseModel switchHotWaterMeterOff(OperateThirdDeviceRequestModel operateThirdDeviceRequestModel) throws Exception {
        return switchOnOrOff(operateThirdDeviceRequestModel, YinTongDevTypeEnum.HOT.getCode(), yintongFreezeUrl);
    }

    /**
     * 热水表开阀供水
     * @param operateThirdDeviceRequestModel
     * @return
     */
    @Override
    public OperateThirdDeviceResponseModel switchHotWaterMeterOn(OperateThirdDeviceRequestModel operateThirdDeviceRequestModel) throws Exception {
        return switchOnOrOff(operateThirdDeviceRequestModel, YinTongDevTypeEnum.HOT.getCode(), yintongUnfreezeUrl);
    }

    /**
     * 冷水表开阀供水
     * @param operateThirdDeviceRequestModel
     * @return
     */
    @Override
    public OperateThirdDeviceResponseModel switchColdWaterMeterOn(OperateThirdDeviceRequestModel operateThirdDeviceRequestModel) throws Exception {
        return switchOnOrOff(operateThirdDeviceRequestModel, YinTongDevTypeEnum.COLD.getCode(), yintongUnfreezeUrl);
    }


    /**
     * 固定请求头内容
     */
    private static final Map<String, String> header = Maps.newHashMap();

    static {
        header.put("Content-Type", "application/json");
    }


}
